package com.oly.cms.web.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.YamlMapFactoryBean;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson2.JSONObject;
import com.oly.cms.common.domain.entity.CmsTheme;
import com.oly.cms.common.model.properties.OlyThemeConfigProperties;
import com.oly.cms.common.model.support.ThemeTreeNode;
import com.oly.cms.common.utils.ZipUtils;
import com.oly.cms.web.service.IWebThemeService;
import com.grace.common.enums.SysConfigGroups;
import com.grace.common.exception.ServiceException;
import com.grace.common.utils.StringUtils;
import com.grace.common.utils.file.FileUtils;
import com.grace.oss.enums.OlyStageRoot;
import com.grace.oss.service.impl.NativeOssHandler;

@Service
public class WebThemeServiceImpl implements IWebThemeService {

    @Autowired
    private NativeOssHandler ossHanded;

    @Override
    public int deleteByName(String themeName) throws FileNotFoundException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public CmsTheme selectThemeByUsed() {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void uploadTheme(MultipartFile file, boolean cover) throws IOException {
        String floadName = FilenameUtils.getBaseName(file.getOriginalFilename());
        if (SysConfigGroups.getValues().contains(floadName)) {
            throw new ServiceException("主题名不被系统允许!");
        }
        String fileName = FilenameUtils.getName(file.getOriginalFilename());
        // 主题文件
        File themeFile = Paths.get(OlyStageRoot.THEME_DIR.getOnlyCodeRoot(fileName)).toFile();
        // 主题文件夹
        File themeFload = Paths.get(OlyStageRoot.THEME_DIR.getOnlyCodeRoot(floadName)).toFile();
        // 文件夹存在
        if (themeFload.exists() && themeFload.isDirectory()) {
            if (cover) {
                ossHanded.ossAppointUpload(file, OlyStageRoot.THEME_DIR, fileName);
                // log.info("主题已覆盖");
            } else {
                throw new ServiceException("主题未上传,因为文件已经存在,你选择的是不覆盖上传！");
            }
        } else {
            ossHanded.ossAppointUpload(file, OlyStageRoot.THEME_DIR, fileName);
            // log.info("主题已经上传！");
        }
        // 解压到当前目录
        ZipUtils.unZipFiles(themeFile.getAbsolutePath(), themeFile.getParent());
        // 删除压缩文件
        ZipUtils.deleteDir(themeFile.getAbsoluteFile());
    }

    /**
     * 读取配置文件
     */
    @Override
    public Object selectThemeConfigSetting(String themeName) {
        File themeYaml = Paths
                .get(OlyStageRoot.THEME_DIR.getOnlyCodeRoot(themeName),
                        OlyThemeConfigProperties.THEME_INFO.defaultValue())
                .toFile();
        if (themeYaml.exists() && !themeYaml.isDirectory()) {
            YamlMapFactoryBean yamMap = new YamlMapFactoryBean();
            FileSystemResource fileResource = new FileSystemResource(themeYaml);
            yamMap.setResources(fileResource);
            return yamMap.getObject();
        } else {
            throw new ServiceException("获取主题说明异常");
        }
    }

    @Override
    public Object selectThemeConfigForm(String themeName) {
        String jsonString = FileUtils.readFileContent(Paths
                .get(OlyStageRoot.THEME_DIR.getOnlyCodeRoot(themeName),
                        OlyThemeConfigProperties.THEME_CONFIG_FORM.defaultValue()));
        JSONObject jsonObject = JSONObject.parseObject(jsonString);
        return jsonObject;
    }

    @Override
    public String selectUseTheme() throws FileNotFoundException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public List<ThemeTreeNode> selectThemeFileTree(String path) {
        if (StringUtils.isEmpty(path)) {
            path = "";
        }
        List<ThemeTreeNode> themeTreeNodes = new ArrayList<>();
        // 获取主题路径
        final File themesPath = new File(OlyStageRoot.THEME_DIR.getOnlyCodeRoot(""));
        listFile(themesPath, path, themeTreeNodes);
        return themeTreeNodes;

    }

    /**
     * 遍历主题文件
     * 
     * @param dir
     * @param prefix
     * @param themeList
     */
    private void listFile(File dir, String prefix, List<ThemeTreeNode> themeList) {
        File[] files = dir.listFiles();
        if (null != files) {
            for (File file : files) {
                ThemeTreeNode themeTreeNode = new ThemeTreeNode();
                themeTreeNode.setParentId(prefix);
                themeTreeNode.setpId(prefix);
                themeTreeNode.setId(prefix + "/" + file.getName());
                themeTreeNode.setName(file.getName());
                themeTreeNode.setTitle(file.getName());
                if (file.isDirectory()) {
                    themeTreeNode.setParent(file.isDirectory());
                    listFile(file, prefix + "/" + file.getName(), themeList);
                }
                themeList.add(themeTreeNode);
            }
        }
    }

}
